from fastapi import APIRouter, HTTPException

from app1.models.user import User
from app1.schemas.user import UserIn, UserOut, UserUpdate,UserCreate

router = APIRouter(prefix="/users", tags=["用户"])


@router.post("/users", response_model=UserOut)
async def create_user(user: UserIn):
    existing = await User.get_or_none(email=user.email)
    if existing:
        raise HTTPException(status_code=400, detail="邮箱已经存在")
    user_obj = await User.create(**user.dict())
    return user_obj


@router.get("/users/{user_id}", response_model=UserOut)
async def get_user(user_id: int):
    user = await User.get_or_none(id=user_id)
    if not user:
        raise HTTPException(status_code=404, detail="用户不存在")
    return user


# 创建用户
@router.post("", response_model=UserOut)
async def create_user(user: UserCreate):
    exists = await User.get_or_none(email=user.email)
    if exists:
        raise HTTPException(status_code=400, detail="邮箱已经存在")
    user_obj = await User.create(**user.dict())
    return user_obj


# 获取单个用户
@router.get("/{user_id}", response_model=UserOut)
async def get_user(user_id: int):
    user = await User.get_or_none(id=user_id)
    if not user:
        raise HTTPException(status_code=404, detail="用户不存在")
    return user


# 获取所有用户
@router.get("", response_model=list[UserOut])
async def list_users():
    return await User.all()


# 更新用户
@router.put("/{user_id}", response_model=UserOut)
async def update_user(user_id: int, user: UserUpdate):
    user_obj = await User.get_or_none(id=user_id)
    if not user_obj:
        raise HTTPException(status_code=404, detail="用户不存在")
    user_data = user.dict(exclude_unset=True)
    for k, v in user_data.items():
        setattr(user_obj, k, v)
    await user_obj.save()
    return user_obj


# 删除用户
@router.delete("/{user_id}")
async def delete_user(user_id: int):
    delete_count = await User.filter(id=user_id).delete()
    if not delete_count:
        raise HTTPException(status_code=404, detail="用户不存在")
    return {"message": "删除成功"}
